package com.example.demo.util;


import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {

    // 公钥字符串
    private final static String stringPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj9vjjWA5dplKC5SSLnQq4FxjeZF8zGFEFsTFBx5cVsGvLDzE+vSEQj/OqEsL//14v+eRfv7aCgS6evuvIqaoadaDlBEe33B/4Ygl40qpJI1aCJF594Fy17mmV9+1L6YAWXwiuEdhTIa8i8xADR47zHt/rsLiGEykW6f0ykAYQeClinRFAGbtiDODM+3wGzete/tqXVVuQHpfNeX04+pX/RN7CRjWmPJvek0d2vgGeZ+AlwoNzwcnf1IgeoloYwVqokiuD3IkPwia0O87rXsGHLdllu8dfb9BZeCHQ/YBykRc8Irhv4e/xudK/4j3n+6zOTiLYy+sG/+rbIhe5rykZwIDAQAB";
    // 私钥字符串
    private final static String stringPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCP2+ONYDl2mUoLlJIudCrgXGN5kXzMYUQWxMUHHlxWwa8sPMT69IRCP86oSwv//Xi/55F+/toKBLp6+68ipqhp1oOUER7fcH/hiCXjSqkkjVoIkXn3gXLXuaZX37UvpgBZfCK4R2FMhryLzEANHjvMe3+uwuIYTKRbp/TKQBhB4KWKdEUAZu2IM4Mz7fAbN617+2pdVW5Ael815fTj6lf9E3sJGNaY8m96TR3a+AZ5n4CXCg3PByd/UiB6iWhjBWqiSK4PciQ/CJrQ7zutewYct2WW7x19v0Fl4IdD9gHKRFzwiuG/h7/G50r/iPef7rM5OItjL6wb/6tsiF7mvKRnAgMBAAECggEARO19rRqCzfGKidvo4rskZBXAT9pGqoKcJjCnms6QPb1VmmOPmhKYYEnEUdyLZl9jgMeKbgfcHt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vwsGCz97heRnOPbmaRPw42f1IVbe8IppscwyniDW//higkm5wbY3YFK8udAz+IGMVilnoelC";
    // 公钥二进制数组
    private static byte[] binaryPublicKey = Base64.getDecoder().decode(stringPublicKey);
    // 私钥二进制数组
    private static byte[] binaryPrivateKey = Base64.getDecoder().decode(stringPrivateKey);


    static {
//         generatorPublicKeyAndPrivateKey();// 生成公钥和私钥的算法
    }

    private static void generatorPublicKeyAndPrivateKey() {
        // RSA 的公钥私钥生成器
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException("创建RSA加密算法失败");
        }
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PublicKey  aPublic  = keyPair.getPublic();
        PrivateKey aPrivate = keyPair.getPrivate();

        binaryPublicKey = aPublic.getEncoded();
        binaryPrivateKey = aPrivate.getEncoded();

        String publicKey  = Base64.getEncoder().encodeToString(binaryPublicKey);
        String privateKey = Base64.getEncoder().encodeToString(binaryPrivateKey);

        System.out.println(String.format("本次随机生成的公钥：长度(%d),值：%s", publicKey.length(), publicKey));
        System.out.println(String.format("本次随机生成的私钥：长度(%d),值：%s", privateKey.length(), privateKey));
        System.out.println("请妥善保存该公钥以及私钥");
    }


    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 1; i++) {
//            String input = "1234567890" ;
//            String encrypt = encrypt(input);
//            String decrypt = decrypt("hkJGBjmt7TOU9fmYt45sTeBt6K8q6Ukb6EwpmAInokEjfSl+lpmcynMD+jFmYmcErOXgkFTMDKT92fO15GwTI4AYeaGrvI1uqkWocRvi81vSkhRLZzOEN8hA0lDy5bIx4nEfFsM4K1XpFiMT18bd7XOWN1rxwK/kYQ3842DteA3HSpG1StPpPX2lsKr3qnTvBVIRKYU+G7Y3KLljxnuC97zr36erz39vUqGzi86Q+JIOtC3b0E7d7po5E9DurRTZw1DUd9W8T8KlJruxyOUIvXhfCozRYcLObme0V3HFy1NQZobA8K0zaqSTdf3GWATsxtKzTkN5MNAHm1UGUk3CXA==");
//            System.out.println("加密后的结果： " + encrypt);
//            System.out.println("解密后的结果： " + decrypt);
        }
    }

    // 加密
    public static String encrypt(String str) throws Exception {
        byte[] src = str.getBytes(StandardCharsets.UTF_8);
        //base64编码的公钥
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(binaryPublicKey));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");// 获取算法
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);// 初始化算法（加密算法）
        byte[] binaryResult = cipher.doFinal(src);// 运行算法获取结果
        return Base64.getEncoder().encodeToString(binaryResult);// 对结果进行base64编码
    }

    // 解密
    public static String decrypt(String str) throws Exception {
        byte[]        inputByte = Base64.getDecoder().decode(str.getBytes(StandardCharsets.UTF_8));// 对base64的密文进行解码
        RSAPrivateKey priKey    = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(binaryPrivateKey));
        Cipher        cipher    = Cipher.getInstance("RSA");// 获取算法
        cipher.init(Cipher.DECRYPT_MODE, priKey);// 初始化算法（解密算法）
        byte[] binaryResult = cipher.doFinal(inputByte);// 运行算法获取结果
        return new String(binaryResult);
    }

}
